package cn.uc.vip.common.cache;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.uc.vip.common.config.ConfigPropertiesHolder;

/**
 * 
 * 接口或类的说明: 缓存持有者
 *
 * <br>==========================
 * <br> 公司：优视科技
 * <br> 开发：zhangxx2@ucweb.com
 * <br> 版本：1.0
 * <br> 创建时间：2011-3-10
 * <br>==========================
 */
public class CacheHolder {
    private final Logger logger = LoggerFactory.getLogger(getClass());

    private final boolean isTurnedOn;
    private final boolean isNullCache;

    /**
     * 缓存接口
     */
    private final ICache<String, Object> cache;

    public ICache<String, Object> getCache() {
        return cache;
    }

    public CacheHolder(ICache<String, Object> cache) {
        this(cache, ConfigPropertiesHolder.get("dataCacheOnOff"));
    }

    public CacheHolder(ICache<String, Object> cache, String cacheOnOff) {
        this.cache = cache;
        if (cacheOnOff == null || "".equals(cacheOnOff.trim()) || "1".equals(cacheOnOff.trim()))
            isTurnedOn = true;
        else
            isTurnedOn = false;

        if (this.cache == null)
            isNullCache = true;
        else
            isNullCache = false;
    }

    /**
     * 从缓存中取指定KEY的对象
     * @param key
     * @return
     */
    public Object get(String key) {
        if (isTurnedOn) {
            try {
                return this.cache.get(key);
            } catch (Throwable t) {
                try {
                    return this.cache.get(key);
                } catch (Throwable t2) {
                    printThrowableMessage(t2, "根据[KEY=" + key + "]从缓存中获取数据时出现异常");
                }
            }
        }
        return null;
    }

    /**
     * 将对象以指定KEY放入到缓存中
     * @param key
     * @param value
     */
    public void put(String key, Object value) {
        if (isTurnedOn) {
            try {
                this.cache.put(key, value);
            } catch (Throwable t) {
                try {
                    this.cache.put(key, value);
                } catch (Throwable t2) {
                    printThrowableMessage(t2, "将[KEY=" + key + "value=" + value + "]放入缓存中时出现异常");
                }
            }
        }
    }

    /**
     * 将对象以指定KEY放入到缓存中
     * @param key
     * @param value
     * @param ttl 单位为秒数
     */
    public void put(String key, Object value, int ttl) {
        if (isTurnedOn) {
            try {
                this.cache.put(key, value, ttl);
            } catch (Throwable t) {
                try {
                    this.cache.put(key, value, ttl);
                } catch (Throwable t2) {
                    printThrowableMessage(t2, "将[KEY=" + key + "value=" + value + "]放入缓存中时出现异常");
                }
            }
        }
    }

    /**
     * 从缓存中移除掉指定KEY的对象
     * @param key
     */
    public boolean remove(String key) {
        if (isTurnedOn) {
            int count = 0;
            label: {
                try {
                    return this.cache.remove(key);
                } catch (Throwable t) {
                    if (++count < 3) {
                        break label;
                    } else {
                        printThrowableMessage(t, "移除缓存中[KEY=" + key + "]的对象时出现异常");
                    }
                }
            }
        }
        return false;
    }

    /**
     * 强行（不关心缓存开关设置）从缓存中取指定KEY的对象
     * @param key
     * @return
     */
    public Object enforceGet(String key) {
        if (isNullCache) {
            logger.error("dataCache is null!");
            return null;
        }

        try {
            return this.cache.get(key);
        } catch (Throwable t) {
            try {
                return this.cache.get(key);
            } catch (Throwable t2) {
                printThrowableMessage(t2, "根据[KEY=" + key + "]从缓存中获取数据时出现异常");
            }
        }
        return null;
    }

    /**
     * 强行（不关心缓存开关设置）将对象以指定KEY放入到缓存中
     * @param key
     * @param value
     */
    public void enforcePut(String key, Object value) {
        if (isNullCache) {
            logger.error("dataCache is null!");
            return;
        }

        try {
            this.cache.put(key, value);
        } catch (Throwable t) {
            try {
                this.cache.put(key, value);
            } catch (Throwable t2) {
                printThrowableMessage(t2, "将[KEY=" + key + "value=" + value + "]放入缓存中时出现异常");
            }
        }
    }

    /**
     * 强行（不关心缓存开关设置）将对象以指定KEY放入到缓存中
     * @param key
     * @param value
     * @param ttl
     */
    public void enforcePut(String key, Object value, int ttl) {
        if (isNullCache) {
            logger.error("dataCache is null!");
            return;
        }

        try {
            this.cache.put(key, value, ttl);
        } catch (Throwable t) {
            try {
                this.cache.put(key, value, ttl);
            } catch (Throwable t2) {
                printThrowableMessage(t2, "将[KEY=" + key + "value=" + value + "]放入缓存中时出现异常");
            }
        }
    }

    /**
     * 强行（不关心缓存开关设置）从缓存中移除掉指定KEY的对象
     * @param key
     */
    public Object enforceRemove(String key) {
        if (isNullCache) {
            logger.error("dataCache is null!");
            return null;
        }

        try {
            return this.cache.remove(key);
        } catch (Throwable t) {
            try {
                return this.cache.remove(key);
            } catch (Throwable t2) {
                printThrowableMessage(t2, "移除缓存中[KEY=" + key + "]的对象时出现异常");
            }
        }
        return null;
    }

    private void printThrowableMessage(Throwable t, String msg) {
        logger.warn(msg, t);
    }

}
